package cn.hs.ph.servlet;

import cn.hs.ph.dao.UserDao;
import cn.hs.ph.dao.impl.UserDaoImpl;
import cn.hs.ph.entity.User;
import cn.hs.ph.util.Result;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 接口： 是被外界调用使用的功能应用方法
 */
@WebServlet("/login")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.设置编码方式
        // 2.处理请求信息
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        // 3.连接数据库，操作数据
        UserDao userDao = new UserDaoImpl();
        User user = userDao.selectByUsernameAndPwd(username, pwd);
        // 4.给出响应
        if(user==null){   // 登录失败
            Result success = Result.error("账号或密码有误！");
            resp.getWriter().write(JSON.toJSONString(success));
        }else{  // 登录成功
            Result result = Result.success("登录成功!");
            resp.getWriter().write(JSON.toJSONString(result));
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
